package com.tca.spring.framework.learning.mybatis.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author zhoua
 * @Date 2021/7/28
 */
@MapperScan(basePackages = "com.tca.spring.framework.learning.mybatis.dao",
        sqlSessionFactoryRef = "sqlSessionFactoryBean")
public class AnnotationMybatisConfig {

    /**
     * 数据源
     * @return
     * @throws PropertyVetoException
     */
    @Bean
    public DataSource dataSource() throws PropertyVetoException {
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
        dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/db_test?serverTimezone=GMT%2B8&useSSL=false&useUnicode=true&characterEncoding=utf-8");
        dataSource.setUser("root");
        dataSource.setPassword("admin");
        return dataSource;
    }

    /**
     * SqlSessionFactoryBean 替代了 SqlSessionFactory
     */
    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        ClassPathResource[] classPathResource = new ClassPathResource[]{new ClassPathResource("mapper/InfoMapper.xml")};
        sqlSessionFactoryBean.setMapperLocations(classPathResource);
        sqlSessionFactoryBean.setDataSource(dataSource);
        return sqlSessionFactoryBean;
    }
}
